#! /bin/sh

# ref: https://blog.csdn.net/weixin_45309916/article/details/128076625
# ref: https://zhuanlan.zhihu.com/p/501455166

vmallocinfo="proc-v.log"
meminfo="proc-m.log"

cp /proc/meminfo $meminfo
cp /proc/vmallocinfo $vmallocinfo

get_meminfo() {
    grep $1 $meminfo | awk '{print $2}'
}

get_mmz_used() {
    if [ ! -f "/proc/media-mem" ]; then
        echo 0
        return
    fi
    mmz_used=`tail -n 1 /proc/media-mem`
    mmz_used=${mmz_used#*used=}
    mmz_used=${mmz_used%%KB*}
    echo $mmz_used
}

show_memory() {
    printf "%-16s %10s KB %6s MB\n" $1 $2 $(($2/1024))
}

## sys free
# free -k
free -m
echo --------------------------------------------------------------------------------
free -lm
echo --------------------------------------------------------------------------------

# <vmallocinfo>
vmalloc_used_byte=$(grep vmalloc $vmallocinfo | awk '{total+=$2}; END {print total}')
vmalloc_used=$(($vmalloc_used_byte/1024))
#show_memory "[vmalloc_used]" $vmalloc_used

# <meminfo>
VmallocUsed=`get_meminfo "VmallocUsed"`
MemTotal=`get_meminfo "MemTotal"`
MemFree=`get_meminfo "MemFree"`
Slab=`get_meminfo "Slab"`
Shmem=`get_meminfo "Shmem:"`
SUnreclaim=`get_meminfo "SUnreclaim"`
PageTables=`get_meminfo "PageTables"`
KernelStack=`get_meminfo "KernelStack"`
Mapped=`get_meminfo "^Mapped:"`
AnonPages=`get_meminfo "AnonPages:"`

HardwareCorrupted=`get_meminfo "HardwareCorrupted"`
Bounce=`get_meminfo "Bounce"`


## WAY-1
# kernel mem: https://zhuanlan.zhihu.com/p/585813632
# >> Slab+ `VmallocUsed` + PageTables + KernelStack + HardwareCorrupted + Bounce + X
memory=$(( $vmalloc_used + $Slab + $PageTables + $KernelStack + $HardwareCorrupted + $Bounce ))
#show_memory "[Kernel-Slab]" $memory
memory=$(( $vmalloc_used + $SUnreclaim + $PageTables + $KernelStack + $HardwareCorrupted + $Bounce ))
#show_memory "[Kernel-SU]" $memory

## WAY-2, Android way
# ref: https://zhuanlan.zhihu.com/p/501455166
# ref: http://aospxref.com/android-13.0.0_r3/xref/frameworks/base/core/java/com/android/internal/util/MemInfoReader.java

# why VmallocUsed is always 0?
# -ref: https://blog.csdn.net/vichie2008/article/details/49126399
# -ref: https://blog.csdn.net/weixin_42262944/article/details/121060622
memory=$(( $Shmem + $SUnreclaim + $VmallocUsed + $PageTables + $KernelStack ))
show_memory "[Kernel-Android]" $memory 

## My Way
memory=$(( $vmalloc_used + $SUnreclaim + $PageTables + $KernelStack ))
show_memory "[Kernel]" $memory 

## MMZ
show_memory "[MMZ]" `get_mmz_used`

# ref: https://zhuanlan.zhihu.com/p/93228929
# sum(PSS); grep Pss /proc/[1-9]*/smaps |awk '{total+=$2}; END {print total}'
memory=$(( $Mapped + $AnonPages ))
show_memory "[Process]" $memory 
